﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Core.DynamicForm.OperationWebService;
using Kingdee.BOS.Core.DynamicService;
using Kingdee.BOS.DataEntity.Metadata.Service;
using System.Windows.Forms;
using Kingdee.BOS.Util;
using System.ComponentModel;
using Kingdee.BOS.WebApi.Client;
using Newtonsoft.Json.Linq;
using Kingdee.K3.FIN.Core.Object.IV.GoldenTax.TaxManagementSystem;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Authentication;
using Kingdee.BOS.Log;
using System.Security.Policy;
using Kingdee.BOS.BusinessEntity.BusinessFlow;


namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 电子票据签收单操作插件
    /// </summary>
    /// <remarks>
    /// 功能：电子票据签收单据选择数据行，点击生成按钮，生成待认领清单
    /// 创建人：wzx
    /// 创建日期：2024.6.26
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    [Description("电子票据签收单据同步生成待认领清单")]
    [HotUpdate]
    public class ElectronicBillsService : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            #region 基本信息——文本字段
            //收票组织
            e.FieldKeys.Add("FCollectBillOrgId");
            //票面金额
            e.FieldKeys.Add("FAmount");
            //票据类型
            e.FieldKeys.Add("FDraftType");
            //发票号码
            e.FieldKeys.Add("FInvoiceNumer");
            //出票日
            e.FieldKeys.Add("FIssueDate");
            //到期日
            e.FieldKeys.Add("FDueDate");
            //币别
            e.FieldKeys.Add("FCurrencyId");
            //票据(包)号
            e.FieldKeys.Add("FNoteNo");
            //收款人账号
            e.FieldKeys.Add("FPayeeAccNo");
            //收款银行
            e.FieldKeys.Add("FPayeeBankName");
            //承兑人名称
            e.FieldKeys.Add("FAcceptorAccName");
            //出票人账号
            e.FieldKeys.Add("FDrawerAccNo");
            //付款银行
            e.FieldKeys.Add("FDrawerBankName");
            //出票人
            e.FieldKeys.Add("FDrawerAccName");
            //出票人开户行行号
            e.FieldKeys.Add("FDrawerCnapsCode");           
            //电票收付类型
            e.FieldKeys.Add("FCollectPayType");
            //承兑日期
            e.FieldKeys.Add("FAcceptanceEDate");
            
            #endregion



        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);

            foreach (DynamicObject entity in e.DataEntitys)
            {
                string UserName = this.Context.UserName;
                string FID = Convert.ToString(entity["ID"]);//内码
                string InvoiceNumer = Convert.ToString(entity["InvoiceNumer"]);//发票号码
                string NoteNo = Convert.ToString(entity["NoteNo"]);//票据（包）号
                string DraftType = Convert.ToString(entity["DraftType"]);//票据类型
                string CollectPayType = Convert.ToString(entity["CollectPayType"]);//电票收付类型
                string AcceptanceEDate = Convert.ToString(entity["AcceptanceEDate"]);//承兑日期
                string IssueDate = Convert.ToString(entity["IssueDate"]);//出票日
                string DueDate = Convert.ToString(entity["DueDate"]);//到期日

                DynamicObject CollectBillOrg = entity["CollectBillOrgId"] as DynamicObject;//收票组织   
                string CollectBillOrgNO = "";
                if (CollectBillOrg != null)
                {
                    CollectBillOrgNO = CollectBillOrg["Number"].ToString();
                }
                decimal Amount = 0;
                Amount = Convert.ToDecimal(entity["Amount"]);//票面金额
                string PayeeAccNo = Convert.ToString(entity["PayeeAccNo"]); //收款银行账号 
                string PayeeAccName = Convert.ToString(entity["PayeeAccName"]); //收款人全称

                DynamicObject Currency = entity["CurrencyId"] as DynamicObject;//币别 
                string CurrencyNO = "";
                if (Currency != null)
                {
                    CurrencyNO = Currency["Number"].ToString();
                }

                string DrawerAccName = Convert.ToString(entity["DrawerAccName"]);//出票人名称
                string DrawerAccNo = Convert.ToString(entity["DrawerAccNo"]);//出票人账号
                string DrawerBankName = Convert.ToString(entity["DrawerBankName"]);//付款银行
                string AcceptorAccName = Convert.ToString(entity["AcceptorAccName"]);//承兑人             
                string F_QLTK_GenerateStatus = Convert.ToString(entity["F_QLTK_GenerateStatus"]);//已生成待认领清单
                //未生成待认领清单数据且电票收付类型是应收票据且(票据类型是银行承兑或者是商业承兑)
                if (F_QLTK_GenerateStatus != "True" && CollectPayType == "1" && (DraftType=="2" || DraftType == "1") )
                {
                    K3CloudApiClient client = new K3CloudApiClient("http://10.10.11.100/K3Cloud/");
                    string loginResult = client.LoginByAppSecret(
                    "6642ecc879eb25",//账套
                    UserName,//用户名
                    "278414_Q/dDxcEL5MmaR/8p453Dy99EQq3bToLG",//应用ID
                    "ccecc8d0a50d4fdcb51e2684ee906248",//应用秘钥
                    2052 //中文
                    );


                    Newtonsoft.Json.Linq.JObject loginResultObj = JObject.Parse(loginResult);

                    JToken loginResultType;

                    loginResultObj.TryGetValue("LoginResultType", out loginResultType);
                    var context = this.Context;
                    if (loginResultType != null && loginResultType.Value<Int32>() == 1)
                    {
                        #region JSON
                        // 获取保存Json
                        var saveStr = BuildUploadObj(context);
                        // 转成JObject
                        var saveObj = JObject.Parse(saveStr);
                        //删除不需要传值的字段
                        JObject JO = (JObject)saveObj["Model"];
                        JO.Remove("F_QLTK_ExchangeRate");//汇率
                        JO.Remove("F_DEV_FDATE");//同步CRM日期
                        // 获取Model
                        JToken modelObj = JO;
                        // 设值
                        JObject basedata = new JObject();
                        basedata.Add("FNumber", CollectBillOrgNO);
                        modelObj["F_RDLV_OrgId_83g"] = basedata;//组织
                        modelObj["F_RDLV_SerialNumber"] = InvoiceNumer;//流水号
                        modelObj["F_RDLV_TradingDay"] = IssueDate;//交易日
                        modelObj["F_RDLV_Amount"] = Amount;//交易金额
                        modelObj["F_RDLV_AcceptanceNumber"] = NoteNo;//承兑票号                      
                        basedata = new JObject();
                        basedata.Add("FNumber", PayeeAccNo);
                        modelObj["F_RDLV_Base_w5c"] = basedata;//收款银行账号
                        basedata = new JObject();
                        if (DraftType=="1")//银行承兑
                        {
                            basedata.Add("FNumber", "JSFS06_SYS");
                        }
                        else if(DraftType == "2")//商业承兑
                        {
                            basedata.Add("FNumber", "JSFS07_SYS"); 
                        }
                        
                        modelObj["F_RDLV_SettleType"] = basedata;//结算方式
                        basedata = new JObject();
                        basedata.Add("FNumber", CurrencyNO);
                        modelObj["F_RDLV_CurrencyType"] = basedata;//币别
                        modelObj["F_RDLV_PayerAccount"] = DrawerAccName;//付款方账户名称
                        modelObj["F_RDLV_PayerBankAccount"] = DrawerAccNo;//付款方银行账号
                        modelObj["F_RDLV_PayerOpenBank"] = DrawerBankName;//付款方开户行
                        modelObj["F_RDLV_CDQFR"] = AcceptanceEDate;//承兑签发日
                        modelObj["F_RDLV_CDDQR"] = DueDate;//承兑到期日

                        modelObj["F_RDLV_Drawer"] = DrawerAccName;//出票人
                        modelObj["F_RDLV_Acceptor"] = AcceptorAccName;//承兑人

                        basedata = new JObject();
                        basedata.Add("FNumber", "CNY");
                        modelObj["F_QLTK_BaseCurrency"] = basedata;//本位币
                        basedata = new JObject();
                        basedata.Add("FNumber", "HLTX01_SYS");
                        modelObj["F_QLTK_Exchange"] = basedata;//汇率类型

                        #endregion
                        var R = client.Save("RDLV_PendingCollectionList", Convert.ToString(saveObj));
                        Common.ResultObject resultObject = JsonConvert.DeserializeObject<Common.ResultObject>(R);
                        string IsSuccess = resultObject.result.responseStatus.IsSuccess;
                        string RNumber = resultObject.result.number.ToString();
                        string ErrorMessage = "";
                        if (resultObject.result.responseStatus.Errors.Length > 0)
                        {
                            for (int i = 0; i < resultObject.result.responseStatus.Errors.Length; i++)
                            {
                                ErrorMessage = ErrorMessage + "(" + i.ToString() + ")" + resultObject.result.responseStatus.Errors[i].FieldName + resultObject.result.responseStatus.Errors[i].Message + ";\t";
                            }
                        }
                        bool bIsSuccess = Convert.ToBoolean(IsSuccess);
                        if (bIsSuccess)//如果保存成功
                        {
                            IOperationResult operationResult = new OperationResult();
                            operationResult.OperateResult.Add(new OperateResult()
                            {
                                SuccessStatus = true,
                                Message = string.Format("生成待认领清单成功,单据编码为：{0}", RNumber),
                                MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.Warning,
                                PKValue = 0,
                            });
                            this.OperationResult.MergeResult(operationResult);
                            string SQL = string.Format(@"update  T_WB_SigningElectronicBill set F_QLTK_GenerateStatus=1 where FID='{0}'", FID);
                            DBUtils.Execute(context, SQL);
                        }
                        else
                        {
                            IOperationResult operationResult = new OperationResult();
                            operationResult.OperateResult.Add(new OperateResult()
                            {
                                SuccessStatus = false,
                                Message = string.Format("生成待认领清单失败！原因：{0}", ErrorMessage),
                                MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.Warning,
                                PKValue = 0,
                            });
                            this.OperationResult.MergeResult(operationResult);
                            string SQL = string.Format(@"update  T_WB_SigningElectronicBill set F_QLTK_GenerateStatus=0 where FID='{0}'", FID);
                            DBUtils.Execute(context, SQL);
                        }
                    }
                    else//登陆失败
                    {
                        IOperationResult operationResult = new OperationResult();
                        operationResult.OperateResult.Add(new OperateResult()
                        {
                            SuccessStatus = false,
                            Message = string.Format("登录失败！原因：{0}", Enum.GetName(typeof(Common.LogResult), loginResultType.Value<Int32>())),
                            MessageType = Kingdee.BOS.Core.DynamicForm.MessageType.Warning,
                            PKValue = 0,
                        });
                        this.OperationResult.MergeResult(operationResult);
                        string SQL = string.Format(@"update  T_WB_SigningElectronicBill set F_QLTK_GenerateStatus=0 where FID='{0}'", FID);
                        DBUtils.Execute(context, SQL);
                    }
                }
            }
        }


        // 获取Json的方法类
        private static string BuildUploadObj(Context context)
        {
            // SaveDesigner为保存操作的设计组件，其他操作请查询T_MDL_FormOperationType 表格
            var designType = TypesContainer.GetOrRegister("Kingdee.BOS.Business.Bill.OperationService.SaveDesigner,Kingdee.BOS.Business.Bill");
            var designer = Activator.CreateInstance(designType) as OperationWebServiceDesigner;
            designer.OperationId = "Save";
            designer.IsWebApi = true;

            var meta = FormMetaDataCache.GetCachedFormMetaData(context, "RDLV_PendingCollectionList");
            var model = designer.CreateServiceModel(context, meta, null) as FormServiceModel;


            // WebApiParamHelper 为内部封装WebApi帮助类，没有对外发布，需要用发射调用获取JSON
            var webApiHelperClass =
                "Kingdee.BOS.Business.PlugIn.DynamicService.WebApiParamHelper,Kingdee.BOS.Business.PlugIn";
            var webApiHelperType = TypesContainer.GetOrRegister(webApiHelperClass);
            var webApiHelper = Activator.CreateInstance(webApiHelperType);
            var getJsonData = webApiHelperType.GetMethod("GetJSONData", new Type[] { typeof(DTOType), typeof(Boolean) });
            return getJsonData?.Invoke(webApiHelper, new object[] { model?.RequestDTOType, true }).GetString();
        }

    }
}
